package com.device.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.device.dataobject.ro.WxMsgVo;
import com.device.dataobject.ro.WxToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

@Service
public class WxService {
    @Value("${wx.appid}")
    private String appId;

    @Value("${wx.appSecret}")
    private String appSecret;

    final
    RestTemplate restTemplate;

    final
    StringRedisTemplate redisTemplate;
    @Autowired
    public WxService(RestTemplate restTemplate, StringRedisTemplate redisTemplate) {
        this.restTemplate = restTemplate;
        this.redisTemplate = redisTemplate;
    }

    public JSONObject getWxUserInfo(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session" +
                "?appid={1}&secret={2}&js_code={3}&grant_type=authorization_code";
        String result = restTemplate.getForObject(url, String.class, appId, appSecret, code);
        return JSON.parseObject(result);
    }

    public JSONObject pushMessage(WxMsgVo wxMsgVo) {
        RestTemplate restTemplate = new RestTemplate();

        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getWxToken();

        ResponseEntity<String> responseEntity =
                restTemplate.postForEntity(url, wxMsgVo, String.class);
        return JSONObject.parseObject(responseEntity.getBody());
    }

    /**
     * 从缓存获取token，如果token失效，则刷新
     */
    public String getWxToken() {
        String accessKey = "wxtoken_" + appId;
        String accessToken = redisTemplate.opsForValue().get(accessKey);
        if (StringUtils.isEmpty(accessToken)) {
            // 缓存没有token，从服务器获取
            WxToken wxToken = getWxTokenFromWxServer();

            // 将token存入缓存，ExpiresIn是微信服务器返回的失效时间（秒），设置token在redis的失效时间小于它
            redisTemplate.opsForValue().set(accessKey, wxToken.getAccessToken(), wxToken.getExpiresIn() - 600, TimeUnit.SECONDS);
        }

        return accessToken;
    }

    /**
     * 从微信服务器获取token
     */
    public WxToken getWxTokenFromWxServer() {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> params = new HashMap<>();
        params.put("APPID", appId);  //
        params.put("APPSECRET", appSecret);
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}", String.class, params);
        String body = responseEntity.getBody();
        return JSONObject.parseObject(body, WxToken.class);
    }

    public static JSONObject getUserInfo(String encryptedData, String sessionKey, String iv){
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);

        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + 1;
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, StandardCharsets.UTF_8);
                return JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
